package com.geline.mybatisplus.interceptor.inner;

import cn.hutool.core.util.StrUtil;
import com.geline.mybatisplus.annotation.InitializeId;
import com.geline.mybatisplus.interceptor.EntityInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.beans.BeanMap;

import java.util.Arrays;
import java.util.List;

/**
 * 初始化数据注解拦截器 @InitializeId
 *
 * @author: mx
 * @date: 2024-09-12 09:14
 */
@Slf4j
public class InitializeIdInterceptor extends EntityInterceptor<InitializeId> {

    @Override
    public void handleInsert(InitializeId annotation, Object entity) {
    }

    @Override
    public void handleUpdate(InitializeId annotation, Object entity) {
        boolean allowed = annotation.allowUpdate();
        if(!allowed){
            Object colValue = BeanMap.create(entity).get(StrUtil.toCamelCase(annotation.column()));
            String value = annotation.value();
            List<String> valueList = Arrays.asList(value.split(","));
            if(valueList.contains(colValue.toString())){
                //初始数据，禁止更新操作
                throw new RuntimeException(annotation.errorMsg());
            }
        }
    }

    @Override
    public void handleDelete(InitializeId annotation, Object entity) {
        boolean allowed = annotation.allowDelete();
        if(!allowed){
            Object colValue = BeanMap.create(entity).get(StrUtil.toCamelCase(annotation.column()));
            String value = annotation.value();
            List<String> valueList = Arrays.asList(value.split(","));
            if(valueList.contains(colValue.toString())){
                //初始数据，禁止删除操作
                throw new RuntimeException(annotation.errorMsg());
            }
        }
    }
}
